package com.software.myopiachildren.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.software.myopiachildren.App;
import com.software.myopiachildren.MainActivity;
import com.software.myopiachildren.R;
import com.software.myopiachildren.bean.SensorInfo;
import com.software.myopiachildren.content.Constans;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.utils.sp.SP;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * sensor传感器服务
 */
public class SensorService extends Service {
    private static final String TAG = "SensorService";

    // 传感器
    private SensorManager sensorManager;
    private Sensor sensor;
    private static long startTime = 0L;// 起点时间
    private int duration = 5000;// 每次采样持续时间
    ArrayList<String> temp_record = new ArrayList(); // 暂存5秒内的数据
    ArrayList<Float> direction_record = new ArrayList(); // 暂存5秒内的数据
    ArrayList<SensorInfo> part_record = new ArrayList(); // 暂存5秒内的数据(存三个数值)
    private float[] data = {0.0F, 0.0F, 0.0F};// 接收传感器数据
    StringBuilder localStringBuilder;

    private int isGathering = 0;  // 1:有满足条件  2：5秒收集
    private MediaPlayer mediaPlayer;

    PowerManager.WakeLock wakeLock;//锁屏唤醒

    private final static int GRAY_SERVICE_ID = 1001;

    //定义一个灰色保活service
    public static class GrayInnerService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(GRAY_SERVICE_ID, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        /**
         *  传感器获取频率
         *  Sensor.TYPE_ACCELEROMETER   加速度传感器
         *  Sensor.TYPE_GYROSCOPE   陀螺仪传感器
         *  Sensor.TYPE_LIGHT   环境光线传感器
         *  Sensor.TYPE_MAGNETIC_FIELD   电磁场传感器
         *  Sensor.TYPE_ORIENTATION  方向传感器
         *  Sensor.TYPE_PRESSURE   压力传感器
         *  Sensor.TYPE_PROXIMITY   距离传感器
         *  Sensor.TYPE_TEMPERATURE   温度传感器
         *
         *  传感器获取频率
         *  SensorManager.SENSOR_DEPLAY_FASTEST   最灵
         *  SensorManager.SENSOR_DEPLAY_GAME   游戏使用
         *  SensorManager.SENSOR_DEPLAY_NORMAL   正常频率(较慢)
         *  SensorManager.SENSOR_DEPLAY_UI     最慢(横和竖)
         *
         */
        //获取SensorManager实例
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取Sensor实例
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        //注册滚动事件
        sensorManager.registerListener(mySensorListener, sensor, SensorManager.SENSOR_DELAY_UI);

        acquireWakeLock();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("SensorService", "onStartCommand...");

        //设置service为前台服务，提高优先级
        if (Build.VERSION.SDK_INT < 18) {
            //Android4.3以下 ，隐藏Notification上的图标
            startForeground(GRAY_SERVICE_ID, new Notification());
        } else if(Build.VERSION.SDK_INT>18 && Build.VERSION.SDK_INT<25){
            //Android4.3 - Android7.0，隐藏Notification上的图标
            Intent innerIntent = new Intent(this, GrayInnerService.class);
            startService(innerIntent);
            startForeground(GRAY_SERVICE_ID, new Notification());
        }else{
            //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
//            startForeground(GRAY_SERVICE_ID, new Notification());
        }
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            // 解除注册
            sensorManager.unregisterListener(mySensorListener);
            // 解除播放器
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }

            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
        } catch (Exception e) {
        }
    }


    //获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
    @SuppressLint("InvalidWakeLockTag")
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "SensorService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }


    /**
     * SensorEventListener 接口的实现，需要实现两个方法
     * 方法1 onSensorChanged 当数据变化的时候被触发调用
     * 方法2 onAccuracyChanged 当获得数据的精度发生变化的时候被调用，比如突然无法获得数据时
     */
    private SensorEventListener mySensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
//            Log.e(TAG, "======方位角：" + (float) (Math.round(sensorEvent.values[0] * 100)) / 100);
//            Log.e(TAG, "======倾斜角：" + (float) (Math.round(sensorEvent.values[1] * 100)) / 100);
//            Log.e(TAG, "======滚动角：" + (float) (Math.round(sensorEvent.values[2] * 100)) / 100);

            data[0] = sensorEvent.values[0];
            data[1] = sensorEvent.values[1];
            data[2] = sensorEvent.values[2];
//        tempRecorder(data);


            // 方案二 ：结合三个坐标角度判断
            //   满足条件：values[0] , values[1] , values[2]
            //   满足条件1：任意数值，-90-90， -30-30
            //   满足条件2：任意数值，-30-30， -90-90
            try {
                float direction_bear = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
                float direction_angle = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
                float direction_scroll = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
                if (isGathering == 0) {
                    if (!(((direction_angle > -90 && direction_angle < 90) && (direction_scroll > -30 && direction_scroll < 30)) ||
                            ((direction_angle > -30 && direction_angle < 30) && (direction_scroll > -90 && direction_scroll < 90)))) {
                        Log.e(TAG, "======：-111111");
                        isGathering = 1;
                        startTime = System.currentTimeMillis();// 获取系统当前时间
                    }
                } else if (isGathering == 1) {
                    if (System.currentTimeMillis() - startTime <= duration) {
                        part_record.add(new SensorInfo(direction_bear, direction_angle, direction_scroll));
                        Log.e(TAG, "======：000000");
                    } else {
                        isGathering = 2;
                        int totalAngle = part_record.size();
                        int fillAngle = 0;
                        if (totalAngle > 0) {
                            for (int i = 0; i < totalAngle; i++) {
                                if (!(((part_record.get(i).getDirection_angle() > -90 && part_record.get(i).getDirection_angle() < 90) && (part_record.get(i).getDirection_scroll() > -30 && part_record.get(i).getDirection_scroll() < 30)) ||
                                        ((part_record.get(i).getDirection_angle() > -30 && part_record.get(i).getDirection_angle() < 30) && (part_record.get(i).getDirection_scroll() > -90 && part_record.get(i).getDirection_scroll() < 90)))) {
                                    fillAngle++; // 满足条件的就增加一个
                                    Log.e(TAG, "======：111111");
                                }
                            }

                            // 判断收集数据80%符合预警条件的就及时预警
                            if (fillAngle / totalAngle > 0.1) {
                                // 预警提示音
                                int warning_type = new SP().load(Constant.WARNING_TYPE, 1);
                                if (warning_type == 1) { //系统提示音
                                    Log.e(TAG, "======：222222");
                                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                    mediaPlayer = MediaPlayer.create(App.getContext(), R.raw.moren);
                                    mediaPlayer.start();
                               /* mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*/
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 5秒后警铃关闭，清空暂存数据，重新收集
                                            mediaPlayer.stop();
                                            mediaPlayer.release();
                                            mediaPlayer = null;
                                            startTime = 0L;
                                            part_record.clear();
                                            isGathering = 0;
                                        }
                                    }, 5000);
                                } else if (warning_type == 2) { //用户录音
                                    Log.e(TAG, "======：333333");
                                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                    mediaPlayer = new MediaPlayer();
                                    mediaPlayer.setDataSource(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();
                                /*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*/

                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 5秒后警铃关闭，清空暂存数据，重新收集
                                            mediaPlayer.stop();
                                            mediaPlayer.release();
                                            mediaPlayer = null;
                                            startTime = 0L;
                                            part_record.clear();
                                            isGathering = 0;
                                        }
                                    }, 5000);
                                }
                            } else {
                                // 清空暂存数据，重新收集
                                startTime = 0L;
                                part_record.clear();
                                isGathering = 0;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 方案一 ：单个判断倾斜度(不太精确)
        /*try {
            float direction_angle = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
            if (isGathering == 0) {
                if (direction_angle > 30 || direction_angle < -30) {
                    Log.e(TAG, "======：-111111");
                    isGathering = 1;
                    startTime = System.currentTimeMillis();// 获取系统当前时间
                }
            } else if (isGathering == 1) {
                if (System.currentTimeMillis() - startTime <= duration) {
                    direction_record.add(direction_angle);
                    Log.e(TAG, "======：000000");
                } else {
                    isGathering = 2;

                    int totalAngle = direction_record.size();
                    int fillAngle = 0;
                    if (totalAngle > 0) {
                        for (int i = 0; i < totalAngle; i++) {
                            if ((direction_angle > 30 && direction_angle < 60) || (direction_angle > -60 && direction_angle < -30)) {
                                fillAngle++; // 满足条件的就增加一个
                                Log.e(TAG, "======：111111");
                            }
                        }

                        // 判断收集数据80%符合预警条件的就及时预警
                        if (fillAngle / totalAngle > 0.8) {
                            // 预警提示音
                            int warning_type = new SP().load(Constant.WARNING_TYPE, 1);
                            if (warning_type == 1) { //系统提示音
                                Log.e(TAG, "======：222222");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.moren);
                                mediaPlayer.start();
                               *//* mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*//*
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        direction_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            } else if (warning_type == 2) { //用户录音
                                Log.e(TAG, "======：333333");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                                *//*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*//*

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        direction_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            }
                        } else {
                            // 清空暂存数据，重新收集
                            startTime = 0L;
                            direction_record.clear();
                            isGathering = 0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            Log.i("sensor", "======onAccuracyChanged-----sensor" + sensor + ",acc:" + accuracy);
        }
    };


    /**
     * 将采集到的数据放入动态数组
     *
     * @param data
     */
    private void tempRecorder(float[] data) {
        temp_record = new ArrayList();
        localStringBuilder = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            localStringBuilder.append(String.valueOf(data) + " ");
            // 向localStringBuilder中添加一条数据
        }
        localStringBuilder.append("\t");
        temp_record.add(localStringBuilder.toString());
    }


}
